import { Dep } from './Dep'

export class Observer {
	constructor(data) {
		this.walk(data)
	}

	walk(data) {
		if (!data || typeof data !== 'object') return
		Object.keys(data).forEach((key) => {
			this.defineReactive(data, key, data[key])
		})
	}

	defineReactive(obj, key, value) {
		const self = this
		self.walk(value)
		let dep = new Dep()
		Object.defineProperty(obj, key, {
			get() {
				Dep.nb && dep.addSub(Dep.nb)
				return value
			},
			set(newValue) {
				if (newValue === value) return
				value = newValue
				self.walk(value)
				dep.notify()
			},
		})
	}
}
